package leetcode;

public class Leetcode443 {
    public int compress(char[] chars) {
        int write = 0, anchor = 0; // write为写入指针; anchor标注一段连续字符的起始位置;
        for(int read = 0; read < chars.length; read++){
            // 当达到数组最后位置或连续字符的最后位置
            if(read + 1 == chars.length || chars[read+1] != chars[read]){
                chars[write++] = chars[anchor]; // 写入字符
                if(read > anchor){ // 写入长度
                    for(char c : ("" + (read - anchor + 1)).toCharArray())
                        chars[write++] = c;
                }
                anchor = read + 1;
            }
        }
        return write;
    }
}
